﻿package com.eshore.player;

import java.io.ByteArrayOutputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class DrawCanvasView extends SurfaceView implements
		SurfaceHolder.Callback {

	private SurfaceHolder mHolder;
	private Canvas canvas;
	private DrawThread threader;
	private Paint mPaint = null;

	public DrawCanvasView(Context context) {
		super(context);
		this.mHolder = getHolder();
		this.mHolder.addCallback(this);
		this.mPaint = new Paint();
	}

	public void pause() {
		// Message message = new Message();
		// message.what = 1;
		// handler.sendMessage(message);
	}

	public void drawBMP(Bitmap bitmap) {

		this.canvas = this.mHolder.lockCanvas();
		// 锁定整个画布，在内存要求比较高的情况下，建议参数不要为null
		synchronized (this.mHolder) {
			// if(holder!=null) {
			// bGrid.drawGrid(c);// 画游戏中的网格
			// BBoom.drawBooms(c, booms); // 画游戏中的炸弹
			// bFairy.drawFairy(c);// 画游戏中的主角
			// 画的内容是z轴的，后画的会覆盖前面画的。

			this.canvas.drawBitmap(bitmap, 0, 0, this.mPaint);
			// c.restore();
		}
		try {
			this.mHolder.unlockCanvasAndPost(this.canvas);
		} catch (Exception e) {
		}
		// 更新屏幕显示内容
	}

	public void drawBitmap(Bitmap source) {

		this.canvas = this.mHolder.lockCanvas();
		try {
			synchronized (this.mHolder) {
				if (source != null) {
					this.canvas.drawBitmap(source, 0, 0, this.mPaint);
				}
			}
		} catch (Exception ex) {
		} finally {
			try {
				this.mHolder.unlockCanvasAndPost(this.canvas);
			} catch (Exception e) {
			}
		}
	}

	public void drawBitmap(Bitmap source, int left, int top) {

		this.canvas = this.mHolder.lockCanvas();
		try {
			synchronized (this.mHolder) {
				if (source != null) {
					this.canvas.drawBitmap(source, left, top, this.mPaint);
				}
			}
		} catch (Exception ex) {
		} finally {
			try {
				this.mHolder.unlockCanvasAndPost(this.canvas);
			} catch (Exception e) {
			}
		}
	}

	public void drawBitmap(Bitmap source, Rect dstrect) {

		this.canvas = this.mHolder.lockCanvas();
		try {
			synchronized (this.mHolder) {
				if (source != null) {
					this.canvas.drawBitmap(source, null, dstrect, this.mPaint);
				}
			}
		} catch (Exception ex) {
		} finally {
			try {
				this.mHolder.unlockCanvasAndPost(this.canvas);
			} catch (Exception e) {
			}
		}
	}

	public void draw(byte[] source) {

		this.canvas = this.mHolder.lockCanvas();
		// 锁定整个画布，在内存要求比较高的情况下，建议参数不要为null
		try {
			synchronized (this.mHolder) {
				// if(holder!=null) {
				// bGrid.drawGrid(c);// 画游戏中的网格
				// BBoom.drawBooms(c, booms); // 画游戏中的炸弹
				// bFairy.drawFairy(c);// 画游戏中的主角
				// 画的内容是z轴的，后画的会覆盖前面画的。

				// Resources res = getResources();
				// Bitmap bmp = BitmapFactory.decodeResource(res,
				// R.drawable.icon);
				//				
				// byte[] tmpbyte = null;
				// tmpbyte = Bitmap2Bytes(bmp);
				//
				// if (tmpbyte != null) {
				// Bitmap bitmap = Bytes2Bimap(tmpbyte);
				// c.drawBitmap(bitmap, 0, 0, mPaint);
				// }

				if (source != null) {
					// byte[] rgbBuf = new byte[304128];;
					// decodeYUV420SP(rgbBuf, source, 352, 288);
					// Bitmap bitmap = Bytes2Bimap(rgbBuf);
					Bitmap bitmap = Bytes2Bimap(source);
					this.canvas.drawBitmap(bitmap, 0, 0, this.mPaint);
				}
				// c.restore();
			}
		} catch (Exception ex) {
		} finally {
			try {
				this.mHolder.unlockCanvasAndPost(this.canvas);
			} catch (Exception e) {
			}
			// 更新屏幕显示内容
		}
	}

	public Bitmap drawableToBitmap(Drawable drawable) {

		Bitmap bitmap = Bitmap
				.createBitmap(
						drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight(),
						drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
								: Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		// canvas.setBitmap(bitmap);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
				.getIntrinsicHeight());
		drawable.draw(canvas);
		return bitmap;
	}

	public Bitmap Bytes2Bimap(byte[] b) {
		if (b.length != 0) {
			return BitmapFactory.decodeByteArray(b, 0, b.length);
		} else {
			return null;
		}
	}

	public byte[] Bitmap2Bytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

	// （YUV --- RGB）
	public static void decodeYUV420SP(byte[] rgbBuf, byte[] yuv420sp,
			int width, int height) {
		final int frameSize = width * height;
		if (rgbBuf == null)
			throw new NullPointerException("buffer 'rgbBuf' is null");
		if (rgbBuf.length < frameSize * 3)
			throw new IllegalArgumentException("buffer 'rgbBuf' size "
					+ rgbBuf.length + " < minimum " + frameSize * 3);

		if (yuv420sp == null)
			throw new NullPointerException("buffer 'yuv420sp' is null");

		if (yuv420sp.length < frameSize * 3 / 2)
			throw new IllegalArgumentException("buffer 'yuv420sp' size "
					+ yuv420sp.length + " < minimum " + frameSize * 3 / 2);

		int i = 0, y = 0;
		int uvp = 0, u = 0, v = 0;
		int y1192 = 0, r = 0, g = 0, b = 0;

		for (int j = 0, yp = 0; j < height; j++) {
			uvp = frameSize + (j >> 1) * width;
			u = 0;
			v = 0;
			for (i = 0; i < width; i++, yp++) {
				y = (0xff & ((int) yuv420sp[yp])) - 16;
				if (y < 0)
					y = 0;
				if ((i & 1) == 0) {
					v = (0xff & yuv420sp[uvp++]) - 128;
					u = (0xff & yuv420sp[uvp++]) - 128;
				}

				y1192 = 1192 * y;
				r = (y1192 + 1634 * v);
				g = (y1192 - 833 * v - 400 * u);
				b = (y1192 + 2066 * u);

				if (r < 0)
					r = 0;
				else if (r > 262143)
					r = 262143;
				if (g < 0)
					g = 0;
				else if (g > 262143)
					g = 262143;
				if (b < 0)
					b = 0;
				else if (b > 262143)
					b = 262143;
				if (yp == 21) {
					Log.d("test", "i:" + i + ",j:" + j + ",yp:" + yp);
				}

				rgbBuf[yp * 3] = (byte) (r >> 10);
				rgbBuf[yp * 3 + 1] = (byte) (g >> 10);
				rgbBuf[yp * 3 + 2] = (byte) (b >> 10);
			}
		}
	}

	public void start() {
		threader = new DrawThread(mHolder);
		threader.start();
	}

	public void stop() {
		threader.doStop();
	}

	class DrawThread extends Thread {
		private SurfaceHolder holder;
		private boolean running = true;
		private int i = 0;

		protected DrawThread(SurfaceHolder holder) {
			this.holder = holder;
		}

		@Override
		public synchronized void start() {
			// TODO Auto-generated method stub

			running = true;
			super.start();
		}

		protected void doStop() {
			running = false;
		}

		public void run() {
			Canvas c = null;
			while (running) {
				i++;
				c = holder.lockCanvas();
				// 锁定整个画布，在内存要求比较高的情况下，建议参数不要为null
				try {
					synchronized (holder) {
						// if(holder!=null) {
						// bGrid.drawGrid(c);// 画游戏中的网格
						// BBoom.drawBooms(c, booms); // 画游戏中的炸弹
						// bFairy.drawFairy(c);// 画游戏中的主角
						// 画的内容是z轴的，后画的会覆盖前面画的。

						// Paint mPaint = new Paint();
						// mPaint.setColor(Color.YELLOW);
						// canvas.drawRect(120, 220, 220, 320, mPaint);
						// c.save();
						// c.rotate(i);
						// mPaint.setColor(Color.GREEN);
						// c.drawRect(110, 20, 230, 63, mPaint);

						// Resources res = getResources();
						// Bitmap bmp = BitmapFactory.decodeResource(res,
						// R.drawable.icon_65_65);
						// byte[] tmpbyte = null;
						// tmpbyte = Bitmap2Bytes(bmp);
						//
						// if (tmpbyte != null) {
						// Bitmap bitmap = Bytes2Bimap(tmpbyte);
						// c.drawBitmap(bitmap, 200, i+10, mPaint);
						// }
						// c.restore();
					}
				} catch (Exception ex) {
				} finally {
					this.holder.unlockCanvasAndPost(c);
					// 更新屏幕显示内容
				}
				// try {
				// sleep(100);
				// } catch (InterruptedException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				// }
			}
		}
	};

	@Override
	protected void dispatchDraw(Canvas canvas) {
		// TODO Auto-generated method stub

		super.dispatchDraw(canvas);
	}

	@Override
	public void draw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.draw(canvas);
	}

	//@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

		// canvas = mHolder.lockCanvas();
		// Paint mPaint = new Paint();
		// mPaint.setColor(Color.YELLOW);
		// canvas.drawRect(120, 220, 220, 320, mPaint);
		//		
		// mHolder.unlockCanvasAndPost(canvas);
	}

	//@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// canvas = mHolder.lockCanvas();
		// Paint mPaint = new Paint();
		// mPaint.setColor(Color.BLUE);
		// canvas.drawRect(100, 200, 200, 300, mPaint);
		//		
		// canvas.save();
		// canvas.rotate(45);
		// mPaint.setColor(Color.RED);
		// canvas.drawRect(150, 10, 200, 60, mPaint);
		// canvas.restore();
		// mHolder.unlockCanvasAndPost(canvas);
	}

	//@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		if (threader != null) {
			threader.doStop();
		}
	}

}